<template>
    <div class="Menu-container content-wrapper">

        <el-row :gutter="20">
            <el-col :span="6">
                <el-row class="margin-bottom-10">
                    <el-col :span="24">
                        <el-form :model="filterApp">
                            <el-select v-model="filterApp.appId" placeholder="所属应用" @change="handleChangeSelect" clearable style="width: 100%">
                                <el-option
                                        v-for="item in appListOptions"
                                        :key="item.key"
                                        :label="item.label"
                                        :value="item.key">
                                </el-option>
                            </el-select>
                        </el-form>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-card class="box-card" :body-style="{ padding: '0px' }">
                            <div class="clearfix card-header">
                                <span><i class="el-icon-menu" style="color:#324057"></i> 权限管理</span>
                                <el-button @click="handleReload" icon="el-icon-refresh" style="float: right; padding: 5px 0px 0px 3px" type="text"></el-button>
                                <el-button @click="handleDelete" icon="el-icon-delete" style="float: right; padding: 5px 10px 0px 3px" type="text"></el-button>
                                <el-button @click="handleUpdate" icon="el-icon-edit" style="float: right; padding: 5px 0px 0px 3px" type="text"></el-button>
                                <el-button @click="handleCreate" icon="el-icon-plus" style="float: right; padding: 5px 0px 0px 3px" type="text"></el-button>
                            </div>
                            <el-tree :data="tree" node-key="id" ref="tree"
                                     v-loading="loading"
                                     highlight-current
                                     :check-strictly="true"
                                     :default-expand-all="true"
                                     :props="defaultProps"
                                     :default-expanded-keys="expandedKey"
                                     @node-click="handleNodeClick"
                            ></el-tree>
                        </el-card>
                    </el-col>
                </el-row>
            </el-col>

            <el-col :span="18">
                <el-row>
                    <el-col :span="24">
                        <table>
                            <tr>
                                <td align="right">所属上级：</td>
                                <td>{{detail.parentName == null ? '无上级' : detail.parentName}}</td>
                            </tr>
                            <tr>
                                <td align="right">名称：</td>
                                <td>{{detail.name}}</td>
                            </tr>
                            <tr>
                                <td align="right">编码：</td>
                                <td>{{detail.code}}</td>
                            </tr>
                            <tr>
                                <td align="right">状态：</td>
                                <td>
                                    <el-tag type="success" size="mini" v-if="detail.status === 1">正常</el-tag>
                                    <el-tag type="danger" size="mini" v-if="detail.status === 2">禁用</el-tag>
                                </td>
                            </tr>
                            <tr>
                                <td align="right">排序：</td>
                                <td>{{detail.orders}}</td>
                            </tr>
                            <tr>
                                <td align="right">备注：</td>
                                <td>{{detail.remarks}}</td>
                            </tr>
                        </table>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <div class="detail-content" style="margin-top: 10px;border-top: 1px solid #d1dbe5;">
                            <span style="display: inline-block; margin: 10px 0;">
                                <el-button type="primary" icon="el-icon-plus" @click="handleOperatorCreate()">创建</el-button>
                            </span>

                            <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%">


                                <el-table-column type="index" width="55" align="center"></el-table-column>

                                <el-table-column label="名称" align="center" width="250">
                                    <template slot-scope="scope"> {{scope.row.name}} </template>
                                </el-table-column>

                                <el-table-column label="编码" align="center" width="400">
                                    <template slot-scope="scope"> {{scope.row.code}} </template>
                                </el-table-column>

                                <el-table-column label="类型" align="center">
                                    <template slot-scope="scope">
                                        <el-tag type="primary" v-if="scope.row.type === 2">组件</el-tag>
                                        <el-tag type="danger" v-if="scope.row.type === 3">操作</el-tag>
                                    </template>
                                </el-table-column>

                                <el-table-column label="状态" align="center">
                                    <template slot-scope="scope">
                                        <el-tag type="success" v-if="scope.row.status === 1">正常</el-tag>
                                        <el-tag type="danger" v-else>禁用</el-tag>
                                    </template>
                                </el-table-column>

                                <el-table-column label="排序" align="center">
                                    <template slot-scope="scope"> {{scope.row.orders}} </template>
                                </el-table-column>

                                <el-table-column label="操作" fixed="right" width="180px" align="center">
                                    <template slot-scope="scope">
                                        <el-button size="small" type="primary" icon="edit" @click="handleOperatorUpdate(scope.row)">编辑</el-button>

                                        <el-button size="small" type="danger" icon="delete" @click="handleOperatorDelete(scope.row)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-col>
                </el-row>
            </el-col>
        </el-row>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" @close="handleCloseDialog">
            <el-row>
                <el-col :md="6" :lg="6">
                    <el-tree :data="tree"
                             node-key="id"
                             highlight-current
                             :default-expanded-keys="expandedKeyEdit"
                             :props="defaultProps"
                             @node-click="handleSetParent"></el-tree>
                </el-col>
                <el-col :md="6" :lg="6">
                    <el-form :model="form" ref="form" :rules="rules" labelPosition="right" labelWidth="80px" style="width: 400px">
                        <el-form-item label="所属应用">
                            <el-select v-model.number="form.appId" clearable  placeholder="请选择所属应用" style="width: 100%;">
                                <el-option
                                        v-for="item in appListOptions"
                                        :key="item.key"
                                        :label="item.label"
                                        :value="item.key"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="所属上级">
                            <el-input v-model="form.parentName" placeholder="请选择所属上级" readonly >
                                <i
                                        class="el-icon-close el-input__icon"
                                        slot="suffix"
                                        @click="handleIconClick">
                                </i>
                            </el-input>
                        </el-form-item>

                        <el-form-item label="名称" prop="name">
                            <el-input v-model="form.name"></el-input>
                        </el-form-item>

                        <el-form-item label="编码" prop="code">
                            <el-input v-model="form.code"></el-input>
                        </el-form-item>

                        <el-form-item label="排序">
                            <el-input-number v-model="form.orders" :min="1"></el-input-number>
                        </el-form-item>

                        <el-form-item label="状态">
                            <el-radio-group v-model.number="form.status">
                                <el-radio class="radio" :label="1">正常</el-radio>
                                <el-radio class="radio" :label="2">禁用</el-radio>
                            </el-radio-group>
                        </el-form-item>

                        <el-form-item label="备注">
                            <el-input
                                    type="textarea"
                                    :autosize="{ minRows: 2, maxRows: 4}"
                                    placeholder="请输入内容"
                                    v-model="form.remarks">
                            </el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="create">确 定</el-button>
                <el-button v-else="" type="primary" @click="update">确 定</el-button>
            </div>
        </el-dialog>


        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogOperatorFormVisible" @close="handleOperatorCloseDialog">
            <el-form :model="operatorForm" ref="operatorForm" labelPosition="right" labelWidth="120px" style="width: 400px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="operatorForm.name"></el-input>
                </el-form-item>

                <el-form-item label="编码" prop="code">
                    <el-input v-model="operatorForm.code"></el-input>
                </el-form-item>

                <el-form-item label="类型">
                    <el-radio-group v-model.number="operatorForm.type">
                        <el-radio class="radio" :label="2">组件</el-radio>
                        <el-radio class="radio" :label="3">操作</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="状态">
                    <el-radio-group v-model.number="operatorForm.status">
                        <el-radio class="radio" :label="1">正常</el-radio>
                        <el-radio class="radio" :label="2">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="排序">
                    <el-input-number v-model="operatorForm.orders" :min="1"></el-input-number>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            placeholder="请输入内容"
                            v-model="operatorForm.remarks">
                    </el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogOperatorFormVisible = false">取 消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="createOperator">确 定</el-button>
                <el-button v-else="" type="primary" @click="updateOperator">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import { created, updated, deleted, selectOne, selectList, selectTree } from '@/api/upms/permission'
    import { selectList as selectListApp } from '@/api/upms/app'
    export default {
        name: 'Permission',
        data() {
            return {
                tree: [],
                loading: false,
                list: [],
                listLoading: false,
                appListOptions: [],
                filterApp: {
                    appId: undefined
                },
                defaultProps: {
                    label: 'name',
                    children: 'children'
                },
                textMap: {
                    create: '新增',
                    update: '编辑'
                },
                dialogStatus: '',
                dialogFormVisible: false,
                dialogOperatorFormVisible: false,
                dialogOperatorStatus: '',
                form: {
                    id: '',
                    pid: '',
                    appId: '',
                    name: '',
                    type: 1,
                    code: '',
                    status: 1,
                    orders: '',
                    remarks: '',
                    parentName: ''
                },
                detail: {
                    id: '',
                    pid: '',
                    appId: '',
                    name: '',
                    type: '',
                    code: '',
                    status: '',
                    orders: '',
                    remarks: '',
                    parentName: ''
                },
                operatorForm: {
                    id: '',
                    pid: '',
                    name: '',
                    type: 3,
                    code: '',
                    status: 1,
                    orders: '',
                    remarks: ''
                },
                expandedKey: [1],
                expandedKeyEdit: [1],
                rules: {
                    name: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ],
                    code: [
                        { required: true, message: '请输入编码', trigger: 'blur' }
                    ]
                }
            }
        },
        created() {
            this.getAppList()
        },
        methods: {
            handleNodeClick(data, node) {
                this.detail = data
                this.detail['parentName'] = node.parent.data.name

                this.operatorForm.pid = data.id
                this.getOperatorList()
            },
            handleCreate() {//添加数据窗口
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.form.appId = this.filterApp.appId
            },
            handleUpdate() {//修改数据窗口
                if(this.detail.id) {
                    selectOne(this.detail.id).then(response => {
                        this.dialogStatus = 'update'
                        this.dialogFormVisible = true
                        this.form = Object.assign({}, response.data)
                        this.form['parentName'] = this.detail.parentName
                        this.expandedKeyEdit = [this.detail.id]
                    })
                } else {
                    this.$message({ type: 'warning', message: '请选择需要修改的权限' })
                }
            },
            handleDelete() {//删除数据
                if(this.detail.id) {
                    this.$confirm('确定要删除？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        deleted(this.detail.id).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getTreeData(this.filterApp.appId)
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })
                    }).catch(() => {
                        this.$message({ type: 'info', message: '已取消删除' })
                    })
                } else {
                    this.$message({ type: 'warning', message: '请选择需要删除的权限' })
                }
            },
            create() {//添加数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        if(this.form.pid) {
                            this.form.appId = null
                        } else {
                            if(!this.form.appId) {
                                this.$message({ type: 'warning', message: '请选择所属应用' })
                                return
                            }
                        }
                        created(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getTreeData(this.filterApp.appId)
                                this.dialogFormVisible = false
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })
                    }
                })
            },
            update() {//修改数据
                this.$refs['form'].validate((valid) => {
                    if(valid) {
                        if(this.form.pid) {
                            this.form.appId = undefined
                        }
                        updated(this.form).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })

                                this.detail = Object.assign({}, this.form)
                                this.getTreeData(this.filterApp.appId)
                                this.dialogFormVisible = false
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })
                    }
                })
            },
            getTreeData(appId) {//获取数据列表
                this.loading = true
                let query = {'type': 1, appId: appId}
                selectTree(query).then(response => {
                    this.tree = response.data
                    this.loading = false
                }).catch(error => {
                    console.log(error)
                    this.loading = false
                })
            },
            getAppList() {
                selectListApp({orderBy: 'orders desc'}).then(response => {
                    for(let item of response.data.list) {
                        this.appListOptions.push({'label': item.name, 'key': item.id})
                    }

                    if(this.appListOptions[0]) {
                        this.filterApp.appId = this.appListOptions[0].key
                        this.getTreeData(this.filterApp.appId)
                    }
                }).catch((error)=>{
                    console.log(error)
                })
            },
            handleChangeSelect(val) {
                this.resetDetail()
                this.getTreeData(val)
                this.list = []
            },
            handleSetParent(data, node) {
                var shut = false
                var sf = this.form

                //判断是否选择自己作为上级
                if(this.form.id == data.id) {
                    this.$message({
                        title: '提示', message: '选择所属上级有误',
                        type: 'info', duration: 2000
                    })
                    return
                }
                //判断选择的上级是否当前修改的上级
                res(node)
                function res(node) {
                    if(!shut) {
                        var n = node.parent
                        if(null != n) {
                            if(sf.id == n.data.id || sf.id == n.data.pid) {
                                shut = true
                            }
                            res(n)
                        }
                    }
                }
                if(shut == true) {
                    this.$message({
                        title: '提示', message: '选择所属上级有误',
                        type: 'warning', duration: 2000
                    })
                    return
                }

                this.form = Object.assign({}, this.form)
                this.form['pid'] = data.id
                this.form['parentName'] = data.name
            },
            handleIconClick(ev) {
                this.form = Object.assign({}, this.form)
                this.form['pid'] = ''
                this.form['parentName'] = ''
                this.form.appId = this.filterApp.appId
            },
            handleCloseDialog() {
                this.resetForm()
            },
            handleReload(){
                this.getTreeData(this.filterApp.appId)
                this.resetDetail()
                this.list = []
            },
            resetForm() {
                if(this.$refs['form']) {
                    this.$refs['form'].resetFields()
                }
                this.form = {
                    id: '',
                    pid: '',
                    appId: '',
                    name: '',
                    type: 1,
                    code: '',
                    status: 1,
                    orders: '',
                    remarks: '',
                    parentName: ''
                }
            },
            resetDetail() {
                this.detail = {
                    id: '',
                    pid: '',
                    appId: '',
                    name: '',
                    type: '',
                    code: '',
                    status: '',
                    orders: '',
                    remarks: '',
                    parentName: ''
                }
            },

            handleOperatorCreate() {
                this.dialogOperatorFormVisible = true
                this.dialogStatus = 'create'
            },
            handleOperatorUpdate(data) {
                this.dialogStatus = 'update'
                selectOne(data.id).then(response => {
                    this.dialogOperatorFormVisible = true
                    this.operatorForm = Object.assign({}, response.data)
                })
            },
            createOperator() {
                this.$refs['operatorForm'].validate((valid) => {
                    if(valid) {
                        this.operatorForm = Object.assign({}, this.operatorForm)
                        console.log()
                        created(this.operatorForm).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getOperatorList()
                            } else {
                                this.$notify({
                                    title: '操作失败', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogOperatorFormVisible = false
                        })
                    }
                })
            },
            updateOperator() {
                this.$refs['operatorForm'].validate((valid) => {
                    if(valid) {
                        updated(this.operatorForm).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getOperatorList()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                            this.dialogOperatorFormVisible = false
                        })
                    }
                })
            },
            handleOperatorDelete(row) {
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getOperatorList()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            getOperatorList() {
                this.listLoading = true
                selectList({'pid': this.operatorForm.pid, 'types': '2,3'}).then(response => {
                    this.list = response.data
                    this.listLoading = false
                }).catch(()=>{
                    this.listLoading = false
                })
            },
            handleOperatorCloseDialog() {
                this.resetOperatorForm()
            },
            resetOperatorForm() {
                this.$refs['operatorForm'].resetFields()
                this.operatorForm = {
                    id: '',
                    pid: this.operatorForm.pid,
                    name: '',
                    type: 3,
                    code: '',
                    status: 1,
                    orders: '',
                    remarks: ''
                }
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
    .card-header{
        border-bottom: 1px solid #d1dbe5; padding: 15px 20px 15px 7px;
    }
    .el-card__body{
        .el-tree{
            border: 0px;
        }
    }
</style>